package com.heima.wemedia.filter;


import com.heima.wemedia.config.GatewayAuthConfig;
import com.heima.wemedia.util.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.List;

@Component
@Slf4j
public class AuthorizeFilter implements GlobalFilter {
    /**
     * 全局过滤器
     * @param exchange   请求和响应参数
     * @param chain   链   用来放行
     * @return
     */

    @Autowired
    private GatewayAuthConfig gatewayAuthConfig;
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //过滤方法

        //1.获取请求参数和响应参数,与servletRequest不一样

        //List<String> allowUrls = Arrays.asList("/login/in");

        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        //2.判断是不是放行的路径
        String path = request.getURI().getPath();
        List<String> allowUrls = gatewayAuthConfig.getAllowUrls();
        System.out.println(allowUrls);
        if (allowUrls!=null&&allowUrls.size()>0){
            for (String allowUrl : allowUrls) {
                if (path.endsWith(allowUrl)) {
                    return chain.filter(exchange);//放行请求
                }
            }
        }


        //3.获取请求头中的token信息
        String token = request.getHeaders().getFirst("token");
        //4.token不存在,直接终止请求,返回401
        if (StringUtils.isBlank(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        //5.解析token,解析失败,终止请求.返回401

        try {
            Claims claimsBody = AppJwtUtil.getClaimsBody(token);//得到主体,载荷
            int i = AppJwtUtil.verifyToken(claimsBody);//验证token有没有过期,载荷里面有失效时间
            //-1：有效，0：有效，1：过期，2：过期
            if (i < 1) {
                Integer userId = (Integer) claimsBody.get("id");//当map来用
                log.info("网关过滤器检验token成功,当前登录用户ID==>{}", userId);//网关的过滤器解析token,得到userId
                //6.获取到token中存储的userId,将userId写到请求头中,转发到其他微服务中
                ServerHttpRequest newRequest = request.mutate().header("userId", String.valueOf(userId)).build();
                ServerWebExchange exchange1 = exchange.mutate().request(newRequest).build();//改变原来的状态
                return chain.filter(exchange1);//转发到其他微服务
            }
        } catch (Exception e) {
            log.error("解析token失败=={}", e.getMessage());
        }

        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();//终止

    }
}
